package com.hh.eduorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hh.commonutils.Result;
import com.hh.eduorder.entity.Order;
import com.hh.eduorder.mapper.OrderMapper;
import com.hh.eduorder.service.client.CourseClient;
import com.hh.eduorder.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.eduorder.service.client.UcenterClient;
import com.hh.eduorder.utils.OrderNoUtil;
import com.hh.vo.CourseVoGloabl;
import com.hh.vo.UcenterMemberVoGloabl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author huhuan
 * @since 2022-02-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UcenterClient ucenterClient;
    @Autowired
    private CourseClient courseClient;

    @Override
    public String createOrders(String courseId, String memberIdByJwtToken) {
        CourseVoGloabl course = courseClient.getCourseByIdFeign(courseId);
        UcenterMemberVoGloabl ucenterMenberById = ucenterClient.getUcenterMenberById(memberIdByJwtToken);

        if (course == null || ucenterMenberById == null) {
            throw new RuntimeException("生成订单信息出错!");
        }

        Order order = new Order();
        order.setOrderNo(OrderNoUtil.getOrderNo());
        order.setCourseId(course.getId());
        order.setCourseCover(course.getCover());
        order.setCourseTitle(course.getTitle());
        order.setTeacherName(course.getTeacherName());
        order.setMemberId(ucenterMenberById.getId());
        order.setNickname(ucenterMenberById.getNickname());
        order.setMobile(ucenterMenberById.getMobile());

        orderMapper.insert(order);

        return order.getOrderNo();
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        Order order;
        if (!StringUtils.isEmpty(orderNo)) {
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo);
            order = orderMapper.selectOne(wrapper);
        } else {
            throw new RuntimeException("订单号为空！");
        }
        return order;
    }

    @Override
    public int getOrderInfoStatus(String courseId,String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        Order order = orderMapper.selectOne(wrapper);
        if (order == null) {
            return 0;
        } else {
            return order.getStatus();
        }
    }
}
